<template>
	<cl-page>
		
		<cl-confirm ref="Confirm"> </cl-confirm>
		<scroll-view :scroll-top="scrollTop" scroll-y class="list" :style="'height:'+scrollHeight+'px'"
					:scroll-with-animation="true">
		<view class="p-20">
			<view class="topic">
				<view class="topic-top">
					<view class="page-content-img">
						<img :src="detail.functionImage" alt="">
					</view>
					<view class="">
						<view class="text-base">
							{{detail.functionName}}
						</view>
						<view class="text-desc">
							{{detail.functionDesc}}
						</view>
					</view>
				</view>
				<view>
					<cl-form ref="Form" v-model="form" :rules="rules" :label-position="'top'">
						<cl-form-item label="创作名称" prop="title">
							<cl-input v-model="form.title"></cl-input>
						</cl-form-item>
						<cl-form-item :label="item.label" :prop="item.isProp" v-for="(item,index) in detail.isForm"
							:key="index">
							<cl-input v-model="form['value'+index]" v-if="item.name=='text'"
								:placeholder="item.props.placeholder"></cl-input>
							<cl-textarea v-model="form['value'+index]" :showConfirmBar="false" :placeholder="item.props.placeholder" v-else />
						</cl-form-item>
					</cl-form>
					<view style="padding-top:2rem;margin-bottom:20rpx">
						<cl-button fill @tap="submit" type="primary" :loading="loading">{{list.length==0?'提交':loading?'生成中':'重新生成'}}</cl-button>
					</view>
				</view>
			</view>
		</view>
		<view class="p-20" v-if="list.length>0">
			<view v-for="(item, index) in list" :key="index">
				<cl-divider background-color="rgb(250,249,249)" v-if="item.time">{{item.time}}</cl-divider>
				<view class="item">
					<view class="animate-absolute" v-if="item.loading">
						<view class="animate-span">
							<view class="animate-ping"></view>
							<view class="relative inline-flex h-2 w-2 rounded-full bg-primary-60%"></view>
						</view>
					</view>
					<view class="content">
						<view class="text" v-if="item.content">
							<mp-html :selectable="true" :content="marked.parse(item.content)" />
							<view class="item-flex" v-if="!item.loading">
								<view class="item-flex-img">
									<image src="@/static/follow.svg" mode="aspectFill"></image>
								</view>
								<view class="item-flex-img" @click="setClipboardData(item.content)">
									<image src="@/static/copy.svg" mode="aspectFill"></image>
								</view>
								<view class="item-flex-img"  @click="deleteList(item.id,index)">
									<image src="@/static/delete.svg" mode="aspectFill"></image>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view style="padding-top:2rem;margin-bottom:20rpx">
				<cl-button fill @tap="submit" type="primary" :loading="loading">{{list.length==0?'提交':loading?'生成中':'重新生成'}}</cl-button>
			</view>
		</view>
		</scroll-view>
	</cl-page>
</template>

<script setup >
	import {
		reactive,
		ref,
		nextTick,
		onMounted,
		getCurrentInstance,
		onBeforeMount
	} from "vue";
	import {
		onShow,
		onShareAppMessage,
		onLoad
	} from "@dcloudio/uni-app";
	import {
		useStore,
		useCool
	} from "/@/cool";
	import moment from 'moment';
	import {
		marked
	} from "marked";
	import {
		useUi
	} from "/@/ui";
	import hljs from "highlight.js/lib/core";
	import "highlight.js/styles/monokai-sublime.css";
	import bash from "highlight.js/lib/languages/bash";
	import javascript from "highlight.js/lib/languages/javascript";
	import typescript from "highlight.js/lib/languages/typescript";
	import json from "highlight.js/lib/languages/json";
	import python from "highlight.js/lib/languages/python";
	import sql from "highlight.js/lib/languages/sql";
	import java from "highlight.js/lib/languages/java";
	import shell from "highlight.js/lib/languages/shell";
	import php from "highlight.js/lib/languages/php";
	import go from "highlight.js/lib/languages/go";
	hljs.registerLanguage("bash", bash);
	hljs.registerLanguage("javascript", javascript);
	hljs.registerLanguage("typescript", typescript);
	hljs.registerLanguage("json", json);
	hljs.registerLanguage("python", python);
	hljs.registerLanguage("sql", sql);
	hljs.registerLanguage("java", java);
	hljs.registerLanguage("shell", shell);
	hljs.registerLanguage("php", php);
	hljs.registerLanguage("go", go);
	marked.setOptions({
		renderer: new marked.Renderer(),
		highlight: function(code) {
			return "<view class='code'>" + hljs.highlightAuto(code).value + "</view>";
		},
		pedantic: false,
		gfm: true,
		tables: true,
		breaks: false,
		sanitize: false,
		smartLists: true,
		smartypants: false,
		xhtml: false
	});
	const {
		user
	} = useStore();
	const {
		service,
		storage
	} = useCool();
	const ui = useUi();
	const options = reactive < any > ({
		NumberResults: [{
				label: "一个",
				value: 1
			},
			{
				label: "两个",
				value: 2
			} 
		]
	});
	const detail = ref({});
	const id = ref("")
	const Form = ref < HTMLElement > ('ClForm');
	const Confirm = ref < HTMLElement > ('ClConfirm');
	const form = ref({
		title: "New Project - " + moment().format("yyyy/MM/DD HH:mm:ss")
	});
	const rules = reactive({
		title: {
			required: true,
			message: "创作名称不能为空"
		}
	});
	let number = ref(0);
	const time=ref(null)
	const loading = ref(false);

	function submit() {
		Form.value?.validate((valid, errors) => {
			if (valid) {
				time.value=moment().format("yyyy-MM-DD HH:mm:ss")
				number.value=0
				send()
			}
		});
	}
	function setClipboardData(data){
		uni.setClipboardData({
			data,
			success: function () {
				// ui.showToast("复制成功");
			}
		});
	}
	const projectsId=ref("")
	onLoad(async (options) => {
		if(options.id){
			id.value = options.id
			await getTopInfo()
		}
		if(options.projectsId){
			projectsId.value=options.projectsId
			getProjectInfo()
		}
		
	})
	// 获取记录详情
	function getProjectInfo(){
		service.inktok.chatlog.info({id:projectsId.value}).then(res=>{
			form.value=JSON.parse(res.form)
			service.inktok.chatlog.list({title:res.title,functionId:res.functionId}).then(res1=>{
				res1.forEach(item=>{
					list.value.push({
						time:item.updateTime,
						content:item.content,
						loading: false,
						...item
					})
				})
			})
		})
	}
	const list = ref([]);

	function getTopInfo() {
		return service.inktok.function.info({
			id: id.value
		}).then(res => {
			if (res.form) {
				let isForm = JSON.parse(res.form)
				isForm.forEach((item, index) => {
					if (item.props.required) {
						rules['value' + index] = {
							required: true,
							message: "数据不能为空"
						}
					}
					form.value['value' + index] = ""
					item.isProp = 'value' + index
				})
				res.isForm = isForm
			}
			detail.value = res
			uni.setNavigationBarTitle({
				title: res.functionName + ""
			})
		})
	}
	function deleteList(id,index) {
		if(!id){
			list.value.splice(index,1)
			return
		}
		Confirm.value?.open({
			title: "提示",
			message: "确定要删除吗?",
			callback(action) {
				switch (action) {
					case "confirm":
					service.inktok.chatLog.delete({ids:[id]}).then(res=>{
						list.value.splice(index,1)
						ui.showToast("删除成功");
					})
						break;
	
					case "cancel":
						ui.showToast("已取消");
						break;
	
					case "close":
						ui.showToast("已关闭");
						break;
				}
			},
		});
	}
	onMounted(async () => {
		connect();
	})

	async function connect() {
		if (!user.socket) {
			return
		}
		user.socket.on(user.socketId, (message) => {
			console.log(message)
			let {
				code,
				msg
			} = message
			if (code == 1000) {
				let {
					detail,
					...temp
				} = msg
				let isDetail = list.value.find(item => item.id == msg.id)
				let content = ""
				if (isDetail) {
					let index = list.value.findIndex(item => item.id == msg.id)
					if (msg.detail.choices[0].finish_reason == 'stop') {
						list.value[index].content = msg.text
						list.value[index].loading = false
						loading.value = false
					} else {
						list.value[index].content += msg.delta
					}
				} else {
					if (msg.detail.choices[0].finish_reason == 'stop') {
						content = msg.text
					} else {
						content += msg.delta ? msg.delta : ''
					}
					list.value.push({
						time:moment().format("yyyy-MM-DD HH:mm:ss"),
						content,
						...temp,
						loading: true,
					})
				}
				nextTick(() => {
					scrollToBottom();
				});
			} else {
				loading.value = false;
			}
		});
	}

	function send() {
		if (!loading.value) {
			number.value++
			user.socket.emit("systemMessage", {
				role: "user",
				system: detail.value.system,
				userId: storage.get('userInfo').id,
				form: form.value,
				id:detail.value.id
			});
			loading.value = true
		}
	}
	function scrollToBottom() {
		scrollTop.value = 1000000 + parseInt(Math.random() * 100);
	}
	const scrollTop = ref(0);
	const scrollHeight = ref(0)
	onBeforeMount(() => {
		uni.getSystemInfo({
			success: async (res) => {
				scrollHeight.value = res.windowHeight - res.safeAreaInsets.bottom
			}
		})
	})
	onShow(() => {

	});
	onShareAppMessage(() => {
		return {
			path: "/pages/index/home",
			title: "闯堂兔",
			imageUrl: "/static/share.jpg"
		}
	})
</script>

<style lang="scss" scoped>
	page {
		min-height: 100vh;
	}

	.p-20 {
		// height: 100%;
	}

	.topic {
		width: 100%;
		height: 100%;
		background-color: rgb(255 255 255);
		border: 1px solid rgb(231 231 234);
		border-radius: 0.5rem;
		padding: 0.75rem;
		box-sizing: border-box;

		.topic-top {
			display: flex;
			align-items: center;
			margin-bottom: 2rem;

			.page-content-img {
				width: 60rpx;
				height: 60rpx;
				margin-right: 1rem;

				image {
					width: 100%;
					height: 100%
				}
			}

			.text-base {
				color: rgb(17 20 45);
				font-weight: 800;
				font-size: 1rem;
				margin-bottom: 0.25rem;
			}

			.text-desc {
				color: rgb(178 179 189);
				font-size: 24rpx;

			}
		}
	}

	.item {
		display: flex;
		position: relative;
		margin-bottom: 20rpx;

		.item-flex {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			margin-top:10px;
			.item-flex-img{
				margin-left:30rpx;
				background-color: rgb(242 242 242);
				border-radius: 50%;
				    padding: 0.375rem;
					width:32rpx;
					height:32rpx;
					display:flex;
					align-items:center;
					justify-content: center;
					image{
						width:95%;
						height:95%;
					}
					color: rgb(112 114 129);
			}
		}

		.animate-absolute {
			position: absolute;
			top: 0;
			left: 0;
			z-index: 99;
			width: .5rem;
			height: .5rem;

			.animate-span {
				width: 100%;
				height: 100%;
				position: relative;

				.animate-ping {
					width: 100%;
					height: 100%;
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;
					position: absolute;
					border-radius: 50%;
					background-color: #6b69f890;
					animation: ping 1s cubic-bezier(0, 0, .2, 1) infinite;

					@keyframes ping {

						75%,
						to {
							transform: scale(2);
							opacity: 0
						}
					}
				}

				.rounded-full {
					left: 0;
					right: 0;
					top: 0;
					bottom: 0;
					position: absolute;
					width: 100%;
					height: 100%;
					border-radius: 50%;
					background-color: #6b69f8;
				}
			}

		}

		.content {
			display: block;
			font-size: 28rpx;
			background-color: #fff;
			border-radius: 0.25rem;
			color: rgb(55 65 81);
			box-shadow: 0 0 #0000, 0 0 #0000, 0 0 #0000, 0 0 #0000, 0 4px 6px -1px rgba(0, 0, 0, .1), 0 2px 4px -2px rgba(0, 0, 0, .1);

			.text {
				display: block;
				padding: 20rpx 30rpx;
				line-height: 40rpx;
				user-select: auto;
			}

			.image {
				position: relative;
				width: 400rpx;
				display: block;
				border: 1rpx solid #eee;
				border-radius: 6rpx;
			}

			:deep(.code) {
				display: block;
				background-color: #18222c;
				color: #fff;
				padding: 20rpx;
				margin-top: 20rpx;
				overflow: auto;
				border-radius: 10rpx;
				font-size: 24rpx;
			}
		}

		&.r {
			flex-direction: row-reverse;
		}
	}
</style>